package com.sx.gongzhong.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.ExposureTypeAdapter;
import com.sx.gongzhong.adapter.MultiImageAdapter;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.model.PublicBean;
import com.sx.gongzhong.model.PublicTotalBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.pest.ConvenniceAppealAddPest;
import com.sx.gongzhong.pest.OrgPest;
import com.sx.gongzhong.pest.PublicPest;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IPublicView;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.OrgView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.AudioDialog;
import com.sx.gongzhong.widget.CountEditText;
import com.sx.gongzhong.widget.LoadDialog;
import com.sx.gongzhong.widget.MyPopupWindow;
import com.zero.smallvideorecord.MediaRecorderActivity;
import com.zero.smallvideorecord.model.MediaRecorderConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 便民诉求添加
 * Created by admin on 2018/1/4.
 */
public class AddConvenniceAppealActivity extends BaseActivity implements IPublicView, IVoidView, UploadFileView, OrgView {
    @BindView(R.id.et_content)
    CountEditText etContent;
    @BindView(R.id.tv_current_count)
    TextView tvCurrentCount;
    @BindView(R.id.tv_file_hint)
    TextView tvFileHint;

    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    @BindView(R.id.tv_appeal_type)
    TextView tvAppealType;
    @BindView(R.id.tv_area)
    TextView tvArea;
    private AudioDialog audioDialog;
    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();

    private int max = 500;
    private int FILE_TYPE = 0;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_addconvennice);
        ButterKnife.bind(this);
        setTitleName("诉求新增");
        setTitleRight("提交");
        FILE_TYPE = getIntent().getIntExtra("TYPE", 0);
        if (FILE_TYPE == 0) {
            rvImageRV.setVisibility(View.GONE);
        }
        // 获取诉求类型
        IDataStorage dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        PublicTotalBean bean=dataStorage.load(PublicTotalBean.class,"appealType");
        if (bean!=null&&bean.getChildren()!=null){
           typeBeanList = bean.getChildren();
        }else {
            new PublicPest(this).getPublicList("appealType");
        }
        new OrgPest(this).getOrgList();
        initView();
    }

    private void initView() {
        changeText(tvCurrentCount);
        changehintText(tvFileHint);
        etContent.setMaxNum(max);
        etContent.setOnEditTextCountLisener(new CountEditText.OnEditTextCountLisener() {
            @Override
            public void setCount(int currentCount) {
                tvCurrentCount.setText(currentCount + "/" + max);
                changeText(tvCurrentCount);
            }
        });
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setSelectMax(3);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        adapter.startAudio(new MultiImageAdapter.OnStartPlayAudioClickListener() {
            @Override
            public void startPlayAudio(String path) {
                if (audioDialog!=null){
                    audioDialog.startPlay(path);
                }
            }
        });
    }

    private void changeText(TextView tv) {
        Spannable span = new SpannableString(tv.getText());
        span.setSpan(new ForegroundColorSpan(Color.BLACK), 0, tv.getText().length() - 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(span);
    }

    private void changehintText(TextView tv) {
        Spannable span = new SpannableString(tv.getText());
        span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.c_b2b2b2)), 11, tv.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(span);
    }

    private String address, content,orgId ="";

    @OnClick({R.id.tv_right, R.id.rl_appeal_type, R.id.rl_area})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                BaseUtil.hintKb(this);
                address = tvArea.getText().toString().trim();
                if (BaseUtil.isEmpty(address)){
                    ToastUtils.showToast(AddConvenniceAppealActivity.this,"请选择所属区域");
                    return;
                }
                if (BaseUtil.isEmpty(typeId)){
                    ToastUtils.showToast(AddConvenniceAppealActivity.this,"请选择诉求类型");
                    return;
                }
                content = etContent.getText().toString().trim();
                if (FILE_TYPE == 0) {
                    if (BaseUtil.isEmpty(content)){
                        ToastUtils.showToast(AddConvenniceAppealActivity.this,"请输入诉求内容");
                        return;
                    }
                    addAppealData(null);
                }else {
                    if (selectList.size() == 0){
                        ToastUtils.showToast(AddConvenniceAppealActivity.this,"上传附件");
                        return;
                    }
                    List<File> fileList = new ArrayList<>();
                    for (PhotoBean photoBean : selectList){
                        fileList.add(new File(photoBean.getPath()));
                    }
                    LoadDialog.show(this,"正在上传文件");
                    new UploadFilePest(this).uploadFile(this,fileList);
                }
                break;
            case  R.id.rl_area:
                createPopType(orgBeanList,1);
                break;
            case R.id.rl_appeal_type:
                createPopType(typeBeanList,2);
                break;
        }
    }

    private void addAppealData(List<String> fileIds) {
        LoadDialog.show(AddConvenniceAppealActivity.this, "提交中...");
        new ConvenniceAppealAddPest(this).addConvenniceAppeal(orgId, typeId, content,fileIds);
    }

    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                switch (FILE_TYPE) {
                    case 1://图片
                        PictureSelector.create(AddConvenniceAppealActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.MULTIPLE)
                                .maxSelectNum(max)// 最大图片选择数量 int
                                //.previewImage(true)// 是否可预览图片
                                .enableCrop(true).withAspectRatio(4, 3)
                                .compress(true).compressGrade(Luban.CUSTOM_GEAR)
                                .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case 2://音频
                        if (audioDialog==null){
                            audioDialog=new AudioDialog(AddConvenniceAppealActivity.this);
                            audioDialog.setCancelable(false);
                            audioDialog.getAudioBack(new AudioDialog.AudioCallback() {
                                @Override
                                public void getData(String filePath, int countdown) {
                                    PhotoBean photoBean = new PhotoBean(filePath, ".amr");
                                    selectList.add(photoBean);
                                    if (adapter != null) adapter.notifyDataSetChanged();
                                }
                            });
                        }
                        audioDialog.show(audioDialog.AUDIO_RECODERD);
                        break;
                    case 3://视频
                        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                                .smallVideoWidth(640).smallVideoHeight(480)
                                .recordTimeMax(10 * 1000).maxFrameRate(20)
                                .minFrameRate(8).captureThumbnailsTime(1)
                                .videoBitrate(580000).build();
                        MediaRecorderActivity.goSmallVideoRecorder(AddConvenniceAppealActivity.this,
                                AddConvenniceAppealActivity.class.getName(), config);
                        break;
                }
            } else {
                ToastUtils.showToast(AddConvenniceAppealActivity.this, "最多上传3张");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case MediaRecorderActivity.FOR_RESULT://拍视频
                    String videoUri = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                    if (!TextUtils.isEmpty(videoUri)) {
                        String type = videoUri.substring(videoUri.lastIndexOf("."));
                        selectList.add(new PhotoBean(videoUri, type));
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }


    @Override
    public void showError(String message) {
        LoadDialog.dismiss(AddConvenniceAppealActivity.this);
        ToastUtils.showToast(AddConvenniceAppealActivity.this, message);
    }

    @Override
    public void getPublicList(List<PublicBean> beanLists) {
        typeBeanList = beanLists;
    }

    private List<PublicBean> typeBeanList;
    private List<PublicBean> orgBeanList;

    /**
     * 类型类型
     */
    private String typeId = "";
    private MyPopupWindow popType;
    private ListView listView;

    public void createPopType(final List<PublicBean> beanList,final int type) {
        if (beanList == null || beanList.size() == 0) {
            ToastUtils.showToast(AddConvenniceAppealActivity.this, "没有数据");
            return;
        }
        if (popType == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.pop_exposure_type, null);
            popType = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            popType.setTouchable(true);
            popType.setOutsideTouchable(false);
            popType.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
            listView = (ListView) view.findViewById(R.id.listView);
            view.findViewById(R.id.imv_Cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popType.dismiss();
                }
            });
        }
        if (beanList != null && beanList.size() > 0) {
            ExposureTypeAdapter adapter = new ExposureTypeAdapter(this, R.layout.item_exposure_type, beanList);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (type == 1){//区域
                        tvArea.setText(beanList.get(position).getName());
                        orgId = beanList.get(position).getId();
                    }else  if (type == 2){//类型
                        tvAppealType.setText(beanList.get(position).getName());
                        typeId = beanList.get(position).getId();
                    }
                    popType.dismiss();
                }
            });
        }
        popType.showAsDropDown(findViewById(R.id.toolbar));
    }
    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        LoadDialog.show(this,"正在提交...");
        List<String> fileIds = new ArrayList<>();
        for (PhotoBean b : beans){
            fileIds.add(b.getId());
        }
        addAppealData(fileIds);
    }
    @Override
    public void getOrgListSuccess(List<PublicBean> result) {
        orgBeanList = result;
    }

    @Override
    public void voidView(String str) {
        LoadDialog.dismiss(AddConvenniceAppealActivity.this);
        ToastUtils.showToast(AddConvenniceAppealActivity.this, "添加成功");
        MyRxBus.get().post(new MsgEvent("ConvenniceAppealActivity",1,null));
        finish();
    }
}
